<?php 

class PurchaseController extends Uuch_BaseController {

    public function indexAction() {
		file_put_contents(APPLICATION_PATH."/inUser.txt",date("Y-m-d H:i:s")."  ".Uuch_Util::real_ip()."\r\n",FILE_APPEND);
        $this->appendCss('/css/daigou/daigou.css');
        $this->appendScript('/js/jquery.min.js');
        $this->setTitle('身在海外，随心购遍国货');
    }

    /**
     * 从商品网址中间提取ID
     * @param type $url
     * @return type 
     */
    public function getId($url) {
        $id = '';
        $queryId = array('id', 'mallstItemId');

        foreach ($queryId as $query) {
            $id = $this->query($url, $query);
            if ($id != NULL)
                break;;
        }

        return $id;
    }

    /**
     * 返回URL中的QueryString的值
     * @param type $url
     * @param type $name
     * @return string 
     */
    protected function query($url, $name) {
        $uri = parse_url($url);
        $query = explode('&', $uri['query']);
        $map = array();
        foreach ($query as $key) {
            $str = explode('=', $key);
            if (count($str) > 1)
                $map[$str[0]] = $str[1];
            else
                $map[$str[0]] = '';
        }
        if (array_key_exists($name, $map))
            return $map[$name];
        else
            return NULL;
    }

    /**
     * 代购
     */
    public function agentAction() {
        $this->appendCss('/css/daigou/fill.css');
        $this->appendScript('/js/jquery.min.js')->appendScript('/js/jquery.validate.min.js')
                ->appendScript('/js/messages_cn.js');

				
        $this->view->url = $this->_getParam('url');
        $form = new Application_Form_PurchaseAgent();
        $request = $this->getRequest();

		if($this->view->url)
			file_put_contents(APPLICATION_PATH."/agentAction.txt",$this->view->url."  ".date("Y-m-d H:i:s")."  ".Uuch_Util::real_ip()."\r\n",FILE_APPEND);
        if ($request->isPost()) {
            if ($form->isValid($request->getPost())) {
                if ($request->getPost()) {
                    $sku = $form->getValue('sku');
                    if ($sku == null)
                        $sku = $form->getValue('url'); 

                    $values = $form->getValues();
                    $product = Application_Model_Product::getByUrl($this->_getParam('url'));

                    if (null == $product)
                        $product = new Application_Model_Product();           
                    
                    if($product->Sku != $sku){
                        $product->Id = NULL;
                        $product->Image = $form->getValue('image');
                    }
                    $product->setOptions($values);
                    
                    $product->RemoteImage = $form->getValue('image');
                    $product->ShipFee = $form->getValue('shipFee');
                    $product->Sku = $sku;
                    $product->PropertyAlias = $this->getSafeParam('prop');
                    $product->save();
                    
                    $comm =$this->getSafeParam('comment');
                    $cart = Application_Model_Cart::current();
                    $cart->addCartItem($product, $form->getValue('quantity'), $comm);
                    
                    $this->_helper->redirector('cart');
                }
            }
        }
        $this->view->form = $form;
        $this->view->title = '代购服务';
    }

    /**
     * 购物车
     */
    public function cartAction() {
        $this->appendCss('/css/daigou/fill.css');
        $this->appendScript('/js/jquery.min.js');
        $this->view->cart = Application_Model_Cart::current();
        $this->view->title = '购物车';
    }

    /**
     * 删除一个购物车中的产品
     */
    public function deleteAction() {
        $id = $this->getRequest()->getParam('id');
        $cartItem = new Application_Model_CartItem($id);
        $cartItem->delete();
        $this->_helper->redirector('cart');
    }

    /**
     * 删除购物车中 选中的商品
     */
    public function dellistAction(){
        $idList = $this->getSafeParam("idList");
        $list = substr($idList,0,strlen($idList)-1);
        $res = explode(",",$list);
        foreach($res as $val){
            Application_Model_CartItem::load($val)->delete();
        }
        $this->json(1);
    }
    
    /**
     * 结算页
     */
    public function checkoutAction() {
        $this->appendCss('/css/daigou/fill.css');
        $this->appendScript('/js/jquery.min.js');
        $this->setTitle('核对订单信息');
        $this->checkLogin();
        if ($this->getRequest()->isPost()) {
            $cart = Application_Model_Cart::current();
            $orders = $cart->createOrders();
            $userId = $this->currentUser()->Id;
            $ids='';
            foreach ($orders as $order){
                $order->UserId = $userId;
                $order->save();
                $ids= $ids.$order->Id.',';
            }
            $countOrder = Application_Model_Order::getCountByUserId($userId);
            if($countOrder == 1){
                $accountItem = Application_Model_UserAccount::addAccount($userId);
                $accountItem->TaskExchangeScore(Application_Model_Task::TASK_ORDER);
            }
            $ids = substr($ids, 0,  strlen($ids)-1);
            $cart->clear();
            $this->_helper->redirector('paying', "Pay", null, array('id' =>$ids, 'type' => 2));
        }
        $this->appendCss('/css/daigou/fill.css');
        $this->view->cart = Application_Model_Cart::current(TRUE);
    }    
    
    /**
     * 订单生成后的展示页
     */
    public function orderAction() {
        $this->appendCss('/css/daigou/fill.css');
        $this->title = '订单与生成';
        $this->view->order = new Application_Model_Order($this->getRequest()->getParam('id'));
    }

    /**
     * 采集商品信息ddd
     */
    public function getinfoAction() {
        //TODO 现在本函数所有代码为测试使用，需要修改
        $url = $this->getRequest()->getParam('url');
        //echo APPLICATION_PATH.'/models/readers/ProductReader.php';
        file_put_contents(APPLICATION_PATH."/daigoulog.txt",$url."  ".date("Y-m-d H:i:s")."  ".Uuch_Util::real_ip(),FILE_APPEND);
		$reader = Uuch_Reader_ProductReader::Create($url);
        $product = $reader->getInfo($url);
        $info = new stdClass();

        if ($product == NULL) {
            $info->success = FALSE;
            file_put_contents(APPLICATION_PATH."/daigoulog.txt","    ".$info->success."    "."\r\n",FILE_APPEND);
        } else {
            $info->success = TRUE;
            file_put_contents(APPLICATION_PATH."/daigoulog.txt","    ".$info->success."    "."\r\n",FILE_APPEND);
            $info->url = $product->Url;
            $info->name = $product->Name;
            $info->price = $product->Price;
            $info->image = $product->Image;
            $info->shipFee = $product->ShipFee;
            $info->sku = $product->Sku;
            $info->hasSkus = $product->HasSkus;
            $info->quantity = $product->Quantity;
            $info->shopId = $product->ShopId;
            $info->priceError = $product->PromotionError == TRUE?TRUE:FALSE;
            $skus = array();
            foreach ($product->getSkus() as $sku) {
                $item = new stdClass();
                $item->properties = $sku->Properties;
                $item->price = $sku->Price;
                $item->quantity = $sku->Quantity;
                $item->skuNo = $sku->SkuNo;
                array_push($skus, $item);
            }
            $info->skus = $skus;
            $info->option = $product->getOption();
        }
        $this->view->info = $info;
    }

    public function changeitemAction() {
        $request = $this->getRequest();
        $itemid = $request->getParam('itemid');
        $quantity = $request->getParam('quantity');
        $comment = $request->getParam('comment');
        $selected = $request->getParam('selected');
        $item = Application_Model_CartItem::load($itemid);
        $item->Quantity = $quantity;
        $item->Comment = $comment;
        $item->IsSelected = 1;
        $item->save();
        $this->json(TRUE);
    }

    public function testAction() {
        $reader = new Uuch_Reader_TaobaoReader();
        $product = $reader->getInfo('http://item.taobao.com/item.htm?spm=a230r.1.10.285.kbXH0t&id=13785543625&_u=e1a17gkabab');
        $this->view->product = $product;
        $this->disableLayout();
    }
    
    public function alibabaAction(){
        $reader = new Uuch_Reader_CommonReader();
        $this->json($reader->getInfo('http://detail.1688.com/offer/1233067542.html'));
    }

}

